package com.listen.service.DB;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.listen.common.HttpClientProxy;
import com.listen.model.User;
import com.listen.vo.HeadParmsVO;

public class GanBuXuanYuan extends Thread{
	private final static int SAVE_M_SECONDS = 60000;
	
	@Override
	public void run() {
	}
	
	public static void main(String arsg []) {
		GanBuXuanYuan ganbu = new GanBuXuanYuan();
		User user = new User();
		user.setAddress("http://www.jxgbwlxy.gov.cn");
		user.setCookie("menuIndex=null; JSESSIONID=abcSXJI8f_cr3azIkZSEw; BIGipServerweb_pool_80=101361856.20480.0000");
		user.setType(0);//0必修，1选修
		ganbu.getMyClassList(user);
		
	}
	
	public void getMyClassList(User user) {
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpClientProxy instance = new HttpClientProxy();
		List<User> list = new ArrayList<User>();
		//String url = user.getAddress() + "/student/course!list.action?course.course_type="+ user.getType() +"&init=yes";
		String url = user.getAddress() + "/student/course!list.action";
		String cookie = user.getCookie();
		
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(cookie);
		heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		heads.setUpgradeInsecureRequests("1");
		heads.setContentType("application/x-www-form-urlencoded");
		Map<String, String> maps = new HashMap<String, String>();
	    maps.put("course.course_type", user.getType()+"");
	    maps.put("init","yes");
	    maps.put("rowCount","40");
	    maps.put("currentPage", "1");
	    maps.put("pageSize", "50");
	    
		user.setReferer(url);
		user.setCookie(cookie);
		try {
			Thread.sleep(2000);
			response = instance.sendHttpPost(httpClient, heads, url,maps, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Elements tables = document.select(".dataTable");
			    Elements trs = null;
			    if(tables.size() == 2) {
			    	trs = tables.get(1).select("tr");
			    }else {
			    	trs = tables.select("tr");
			    }
			    for(int i = 1;i<trs.size();i++) {
			    	User u = new User();
		    		u.setAddress(user.getAddress());
		    		u.setCookie(user.getCookie());
			    	Elements tds = trs.get(i).select("td");
			    	for(int j = 0;j < tds.size();j++) {
			    		if(j == 1) {
			    			String title = tds.get(j).select(".jindu").attr("title");
			    			int index = title.indexOf("/");
			    			int allMinute = Integer.parseInt(title.substring(index+1, title.length()-2));//课程时长
			    			int nowMinute = Integer.parseInt(title.substring(0,index-2));
			    			u.setAllNum(allMinute);
			    			u.setNowNum(nowMinute);
			    		}
			    		if(j == 2) {
			    			String onclick = tds.get(j).select("a").attr("onclick");
			    			String courseid = onclick.substring(onclick.indexOf("(")+1, onclick.lastIndexOf(")"));
			    			u.setId(Integer.parseInt(courseid));
			    		}
			    	}
			    	list.add(u);
			    }
			    for(int k = 0;k < list.size() ;k++) {
			    	final User save = list.get(k);
			    	this.checkIsLogin(save);
			    	//Thread thread = new GanBuXueYuanStudy(list.get(k));
			    	//thread.start();
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public synchronized void checkIsLogin(User user) {
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpClientProxy instance = new HttpClientProxy();
		String url = user.getAddress() + "/portal/user!checkIsLogin.action";
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(user.getCookie());
		heads.setReferer(user.getReferer());
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("text/plain;charset=UTF-8");
	    heads.setxRequestedWith("XMLHttpRequest");
    	
		try {
			Thread.sleep(1000);
			response = instance.sendHttpPost(httpClient, heads, url, null);
			int state = response.getStatusLine().getStatusCode();
			String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
			//System.out.println("state="+state);
			if(state == 200 && "1".equals(resMsg)) {
				System.out.println("IsLogin：true");
				isExits(user);
			}else {
				System.out.println("IsLogin：false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public synchronized void isExits(User user) {
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpClientProxy instance = new HttpClientProxy();
		String url = user.getAddress() + "/student/course!isExits.action?userCourse.id="+user.getId();
		
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(user.getCookie());
		heads.setReferer(user.getReferer());
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("text/plain;charset=UTF-8");
	    heads.setxRequestedWith("XMLHttpRequest");
	    
	    //System.out.println(user.getCookie());
	    //System.out.println(url);
	    try {
			response = instance.sendHttpPost(httpClient, heads, url, null);
			int state = response.getStatusLine().getStatusCode();
			String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
			
			if(state == 200 && "1".equals(resMsg)) {
				System.out.println("isExits：true");
				ajaxVideoList(user);
			}else {
				System.out.println("isExits：false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public synchronized void ajaxVideoList(User user) {
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpClientProxy instance = new HttpClientProxy();
		String url = user.getAddress() + "/student/course!ajaxVideoList.action?userCourse.id="+user.getId() + "&select_year=undefined";
		
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(user.getCookie());
		heads.setReferer(user.getReferer());
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("text/plain;charset=UTF-8");
	    heads.setxRequestedWith("XMLHttpRequest");
	    
	    try {
	    	Thread.sleep(1000);
			response = instance.sendHttpPost(httpClient, heads, url, null);
			int state = response.getStatusLine().getStatusCode();
			String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
			//System.out.println("state="+state);
			if(state == 200 && "1".equals(resMsg)) {
				System.out.println("ajaxVideoList：true");
				playNew(user);
			}else {
				System.out.println("ajaxVideoList：false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public synchronized void playNew(final User user) {
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpClientProxy instance = new HttpClientProxy();
		String url = user.getAddress() + "/student/course!playNew.action?userCourse.id="+user.getId() + "&index=0&random="+Math.random()+"&select_year=undefined";
		
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(user.getCookie());
		heads.setReferer(user.getReferer());
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    
	    try {
	    	Thread.sleep(1000);
	    	response = instance.sendHttpGet(httpClient, heads, url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200) {
				System.out.println("playNew：true");
				int nowMinute = user.getNowNum();
				int allMminute = user.getAllNum();
				while(nowMinute <= allMminute) {
					Thread.sleep(SAVE_M_SECONDS);//每隔1分钟保存一次进度，直到课程结束
					addStudyDuration(user);
					nowMinute++;
				}
			}else {
				System.out.println("playNew：false");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void addStudyDuration(final User user) {
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpClientProxy instance = new HttpClientProxy();
		String url = user.getAddress() + "/student/course!addStudyDuration.action";
		
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(user.getCookie());
		heads.setReferer(user.getReferer());
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("text/plain;charset=UTF-8");
	    heads.setxRequestedWith("XMLHttpRequest");
	    heads.setUpgradeInsecureRequests("1");
	    
	    Map<String, String> maps = new HashMap<String, String>();
	    maps.put("id", user.getId().toString());
	    
	    try {
	    	Thread.sleep(1000);
			response = instance.sendHttpPost(httpClient, heads, url,maps,null);
			int state = response.getStatusLine().getStatusCode();
			String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
			//System.out.println("resMsg="+resMsg +"   state="+state);
			if(state == 200 && "success".equals(resMsg)) {
				System.out.println(user.getId() +"-保存数据 result："+resMsg);
			}else {
				System.out.println(user.getId() +"-保存数据 result: "+resMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
}
